package edu.scut.yi.yx.login;


import com.electrotank.electroserver5.extensions.BaseLoginEventHandler;
import com.electrotank.electroserver5.extensions.ChainAction;
import com.electrotank.electroserver5.extensions.LoginContext;
import com.electrotank.electroserver5.extensions.api.value.EsObject;
import com.electrotank.electroserver5.extensions.api.value.EsObjectRO;
import edu.scut.yi.yx.dbmanager.*;
import java.sql.SQLException;

public class LoginEventHandler extends BaseLoginEventHandler{

	private DatabaseJDBCPlugin databasePlugin;
	private static String TABLE_NAME = "USERPASSWORDS";
	
	@Override
	public ChainAction executeLogin(LoginContext context) {
		// TODO Auto-generated method stub
		String username = context.getUserName();
		String query = "SELECT password FROM " + TABLE_NAME + " WHERE username = "+"'"+ username +"'";
		try{
			EsObject msg = databasePlugin.doQuery(query);
			String stroedPassword = null;
			stroedPassword = msg.getEsObjectArray("results")[0].getString("password");
                        
                        if(stroedPassword != null && context.doHashedPasswordsMatch(stroedPassword)){
                            return ChainAction.OkAndContinue;
                        }else 
                            return ChainAction.Fail;
		}catch(SQLException e){
			getApi().getLogger().debug("SQLException for requested query: " + query);
		}
		return ChainAction.Fail;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}

	@Override
	public void init(EsObjectRO parameters) {
		// TODO Auto-generated method stub
		databasePlugin = (DatabaseJDBCPlugin) getApi().getServerPlugin("DatabaseJDBCPlugin");
		
	}
	

}
